<template>
  <div class="ms-list">

    <el-row class="operation">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">
          <icon style="" name="home"></icon>
        </el-breadcrumb-item>
        <el-breadcrumb-item>财务管理</el-breadcrumb-item>
        <el-breadcrumb-item>消费分析</el-breadcrumb-item>
        <el-breadcrumb-item>项目平台消费月报</el-breadcrumb-item>
      </el-breadcrumb>
      <el-button-group>
        <router-link :to="{path: '/customer/item-platform-month-consumption-line',
                           query: {data: this.table.list, search: this.search}}" target="_blank">
          显示图表
        </router-link>
      </el-button-group>
    </el-row>

    <ms-search :data="search.list" @click="updateConditions"></ms-search>

    <el-table
      class="element-table"
      size="small" stripe border
      :data="recombineList"
      :summary-method="getSummaries"
      :show-summary="true"
      :highlight-current-row="true"
      :fit="true">
      <el-table-column prop="itemTitle" label="项目" min-width="100" fixed></el-table-column>
      <el-table-column prop="platformTitle" label="平台" min-width="60" fixed></el-table-column>
      <!--<el-table-column prop="name" :label='search.list[0].value +"年 项目平台消费月报"' class-name="el-table-column-left">-->
        <el-table-column
          v-for="(col, index) in collections"
          :key="index"
          :prop="col.prop"
          :label="col.label"
          min-width="80" align="right" header-align="center">
        </el-table-column>
      <!--</el-table-column>-->
      <el-table-column prop="total" label="合计" min-width="80" align="right" header-align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.total !== '' && scope.row.total !== undefined">{{ Number(scope.row.total).toFixed(2)
            }}</span>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      class="pagination"
      layout="total, sizes, prev, pager, next, jumper"
      :current-page.sync="table.pagination.page"
      :total="table.pagination.totalRow"
      :page-size="table.pagination.pageSize"
      :page-sizes="table.pagination.pageSizes"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange">
    </el-pagination>
  </div>
</template>

<script>
  import MsSearch from '@/components/common/Search.vue'
  import MsConfirmButton from '@/components/common/ConfirmButton.vue'
  import Api from '@/api/customer/platform-month-consumption'
  import ResponseParse from '@/utils/response-parse'
  import { SEARCH_CONDITION } from '@/models/customer/platform-month-consumption'
  import { PLATFORM_LIST } from '@/utils/constants'

  const date = new Date()
  const year = '' + date.getFullYear()
  export default {
    components: {
      MsSearch,
      MsConfirmButton
    },
    data () {
      return {
        search: {
          list: [],
          condition: {}
        },
        table: {
          loading: true,
          list: [],
          pagination: {}
        },
        collections: []
      }
    },
    created () {
      this.search.list = SEARCH_CONDITION
      this.search.condition.year = new Date().getFullYear()
      this.table.list = []
      this.requestList()
    },
    computed: {
      platforms () {
        return PLATFORM_LIST
      },
      recombineList () {
        let platforms = {}
        PLATFORM_LIST.forEach(item => {
          platforms[item.id] = item.title
        })

        // 动态列头数据
        this.collections = []
        for (let i = 1; i <= 12; i++) {
          let keyYear = undefined === this.search.list[0].value ? year : this.search.list[0].value
          let _month = keyYear * 100 + i + ''
          let person = {}
          person.prop = _month
          person.label = i + '月'
          this.collections.push(person)
        }

        let list = []
        let $data = this.table.list['month']
        for (let key in $data) {
          let arrayData = {}
          if (Object.keys($data[key]).length === 0) {
            continue
          }
          let keys = key.split('_')
          // 获取项目名称
          let $items = this.table.list['items']
          for (let item in $items) {
            if (keys[0] === item) {
              arrayData.itemTitle = $items[item]['title']
            }
          }
          // 获取平台名称
          if (keys[1] !== undefined && keys[1] !== '') {
            arrayData.platformTitle = platforms[keys[1]]
          } else {
            arrayData.platformTitle = '未知'
          }
          // 获取数据类型
          const dataType = this.search.condition.dataType
          arrayData.total = 0
          for (let i = 0; i < 12; i++) {
            let p = this.collections[i].prop
            if (dataType === 1) {
              arrayData[p] = ($data[key][p] === undefined ? undefined : $data[key][p]['costCoin']) === undefined ? 0 : $data[key][p]['costCoin']
              arrayData.total += arrayData[p]
            } else if (dataType === 2) {
              arrayData[p] = ($data[key][p] === undefined ? undefined : $data[key][p]['costMoney']) === undefined ? 0 : $data[key][p]['costMoney']
              arrayData.total += arrayData[p]
            } else if (dataType === 3) {
              arrayData[p] = ($data[key][p] === undefined ? undefined : $data[key][p]['serviceCoin']) === undefined ? 0 : $data[key][p]['serviceCoin']
              arrayData.total += arrayData[p]
            } else {
              arrayData[p] = ($data[key][p] === undefined ? undefined : $data[key][p]['costCoin']) === undefined ? 0 : $data[key][p]['costCoin']
              arrayData.total += arrayData[p]
            }
          }
          list.push(arrayData)
        }
        return list
      }
    },
    methods: {
      requestList () {
        this.table.loading = true

        const search = Object.assign({}, this.table.pagination, this.search.condition)
        Api.list({search: search}, response => {
          let status = response.status || 0
          let body = response.data[0].map || {}
          if (status === 200 || status === 204) {
            this.table.list = body
            this.table.pagination = ResponseParse.pagination(response.headers)
//            if (this.table.pagination.totalPage === this.table.pagination.pag) {
//              this.tbHeight = ''
//            } else {
//              this.$set(this, 'tbHeight', this.PHeigh - this.$refs.msSearch.clientHeight)
//            }
          } else {
//            this.tbHeight = ''
            this.table.list = []
            this.$message.error(body.error || '获取数据失败')
          }
          this.table.loading = false
        })
      },
      handleSizeChange (val) {
        this.table.pagination.pageSize = val
        this.requestList()
      },
      handleCurrentChange (val) {
        this.table.pagination.page = val
        this.requestList()
      },
      updateConditions (conditions) {
        this.table.pagination.page = 1
        this.search.condition = conditions
        this.requestList()
      },
      getSummaries (param) {
        const {columns, data} = param
        const sums = []

        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计'
            return
          }
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
          } else {
            sums[index] = ''
          }
          sums[1] = ''
        })
        // 格式化合计后的数据
        for (let i = 2; i < sums.length; i++) {
          if (sums[i] !== 0 && sums[i] !== '') {
            sums[i] = sums[i].toFixed(2)
          }
        }
        return sums
      }
    }
  }
</script>

<style lang="scss" scoped>
  .element-table td {
    height: 37px;
  }

  /*覆盖样式*/
  /*.el-table-column-left {*/
    /*text-align: left !important;*/
  /*}*/
</style>
